Single Number II

Given an array of integers, every element appears three times except for one. Find that single one.

Note:

Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?

Solution:

  1. public class Solution {
  2. public int singleNumber(int[] nums) {
  3. int ones = 0, twos = 0, threes = 0;
  4. for (int i = 0; i < nums.length; i++) {
  5. // twos holds the num that appears twice
  6. twos |= ones & nums[i];
  7. // ones holds the num that appears once
  8. ones ^= nums[i];
  9. // threes holds the num that appears three times
  10. threes = ones & twos;
  11. // if num[i] appears three times
  12. // doing this will clear ones and twos
  13. ones &= ~threes;
  14. twos &= ~threes;
  15. }
  16. return ones;
  17. }
  18. }